'use strict';
import Base from './base.js';
import React from 'react';
import {renderToString} from 'react-dom/server';
import {RouterContext, match, browserHistory} from 'react-router';
import {Provider} from 'react-redux';
import {combineReducers} from 'redux';

import routes from '../../router/routes';
import configureStore from '../../router/store';
import {LOGIN_RECEIVE} from '../../router/actions/login';
import {right_header_change} from '../../router/actions/right';
import reducers from '../../router/reducers';

export default class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async  indexAction() {
        let $this = this;
        //不放在外部了
        const store = configureStore(reducers);
        const routesBase=routes(store.getState());

        //登录状态action处理
        let username = await this.session("username");
        async function loginManage() {
            if (username) {
                await store.dispatch({
                    type: LOGIN_RECEIVE,
                    user: {
                        username: username
                    },
                    isLogin: true
                })
            }
        }
        await loginManage();

        //登录headerRight头显示处理
        async function dealHeaderRight() {
            await store.dispatch(right_header_change($this.http.url));
        }
        await dealHeaderRight();

        match({
            routes:routesBase,
            location: $this.http.req.url
        }, (err, redirectLocation, renderProps) => {
            if (err) {
                $this.displayErrorPage(500);
            } else if (redirectLocation) {
                $this.redirect(redirectLocation.pathname + redirectLocation.search);
            } else if (renderProps) {
                //console.log(store.getState());//得到当前的状态
                const html = renderToString(
                    <Provider store={store}>
                        <RouterContext {...renderProps} />
                    </Provider>
                );
                $this.assign("__html__", html);
                $this.assign("__state__", JSON.stringify(store.getState()));
                $this.display();
            } else {
                $this.displayErrorPage(404);
            }
        });
        //auto render template file index_index.html
        return null;
    }
}